package com.tj.api.task;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.google.common.collect.Lists;
import com.tj.bo.account.client.AccountBalanceChangeService;
import com.tj.bo.account.client.enums.IncomeEnum;
import com.tj.bo.account.client.vo.AccountIncomeVO;
import com.tj.bo.common.conf.config.RedisConfigUtil;
import com.tj.bo.common.conf.util.IpUtils;
import com.tj.bo.trade.client.enums.OrderStatusEnum;
import com.tj.bo.trade.server.dao.BinaryTradeDao;
import com.tj.bo.trade.server.entity.BinaryTradeEntity;
import org.apache.commons.lang3.time.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: binary-option
 * @description 超时关闭交易列表
 * @author: binary
 * @create: 2020-07-01 17:34
 **/
@Component
public class TradeTimeoutTask {

    private static final Logger LOGGER = LoggerFactory.getLogger(TradeTimeoutTask.class);

    @Autowired
    private BinaryTradeDao binaryTradeDao;
    @Autowired
    private AccountBalanceChangeService accountBalanceChangeService;
    @Autowired
    private RedisConfigUtil redisDbConfigUtil;

    /**
     * 关闭超时交易
     */
    @Scheduled(cron="0 0/1 * * * ?")
    public void closeTimeoutOrders(){

        String ip = IpUtils.getIp();
        String taskIp = redisDbConfigUtil.getTaskIp();
        if(!taskIp.equalsIgnoreCase(ip)){
            LOGGER.info("============ IP不匹配不执行任务 taskIp:{}, localIp:{}  ==========", taskIp, ip);
            return;
        }

        List<BinaryTradeEntity> binaryTradeEntities = binaryTradeDao.selectsBinaryTradeListByStatusAndTime(OrderStatusEnum.OPENING.getCode(), null, DateUtils.addMinutes(new Date(), -2));
        if(CollectionUtils.isEmpty(binaryTradeEntities)){
            LOGGER.info("============ 需要关闭的交易列表为空 ==========");
            return;
        }

        ExecutorService executorService = Executors.newFixedThreadPool(20);
        List<String> tradeNos = Lists.newArrayList();
        for(BinaryTradeEntity binaryTradeEntity : binaryTradeEntities){
            tradeNos.add(binaryTradeEntity.getTradeNo());
            executorService.execute(() -> {
                try {
                    binaryTradeEntity.setProfitAmount(binaryTradeEntity.getAmount());
                    binaryTradeEntity.setClosingTime(new Date());
                    binaryTradeEntity.setOrderStatus(OrderStatusEnum.TIMEOUT_CLOSING.getCode());
                    binaryTradeDao.updateByPrimaryKey(binaryTradeEntity);
                    this.cashRecorded(binaryTradeEntity.getUserCode(), binaryTradeEntity.getTradeNo(), binaryTradeEntity.getAmount());
                } catch (Exception e) {
                    LOGGER.error("========== 关闭的交易列表失败，tradeNo:{}, e =========" , binaryTradeEntity.getTradeNo(), e);
                }
            });
        }
        LOGGER.info("============ 关闭的交易列表任务Success,tradeNos:{} ==========", JSONObject.toJSONString(tradeNos));
    }

    private void cashRecorded(String userCode, String tradeNo, BigDecimal profitAmount){
        if(profitAmount.compareTo(BigDecimal.ZERO) > 0){
            AccountIncomeVO accountIncome = new AccountIncomeVO();
            accountIncome.setUserCode(userCode);
            accountIncome.setOrderNo(tradeNo);
            accountIncome.setAmount(profitAmount);
            accountIncome.setGrants(BigDecimal.ZERO);
            accountIncome.setIncomeEnum(IncomeEnum.TRADE_PROFIT);
            accountBalanceChangeService.income(accountIncome);
        }
    }
}
